#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void Useage(const std::string& s)
{
    std::cout << s << ":\n\t" << " ip port\n";
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Useage(argv[0]);
        exit(0);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(socketfd < 0)
    {
        std::cout << "socket create fail" << std::endl;
        exit(1);
    }
    
    // 2. 绑定套接字和网络信息
    // client 要不要 bind ? 一定要，client也需要IP 和 PORT 来标识自身唯一性
    //需不需要显示[类似server bind()]的bind ? 不需要，防止 client port 冲突，client 首次发送数据时，OS 会自动的随机的给client 进行bind 

    std::string message;
    while(true)
    {
        std::cout << "please enter#";
        std::getline(std::cin, message);

        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(ip.c_str());

        ssize_t ret = sendto(socketfd, message.c_str(), message.size(), 0, (const sockaddr*)&server, sizeof server);
        if(ret > 0)
        {
            char buff[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            ssize_t n = recvfrom(socketfd, buff, sizeof(buff) - 1, 0, (sockaddr*)&peer, &len);
            if(n > 0)
            {
                buff[n] = '\0';
                std::cout << "server say : " << buff << std::endl;
            }
        }

    }

    return 0;
}